
<!--suppress ALL -->
<template>
  <div class="app-container">
    <el-form label-width="100px" style="width: 1200px">
      <el-form-item label="名称">
        <el-input v-model="article.title" placeholder="文章名称(随便填写)"/>
      </el-form-item>

      <!-- 分类查询 -->
      <el-form-item label="分类">
        <!-- 一级分类 -->
        <el-select
          v-model="article.clsParentId"
          placeholder="请选择"
          @change="articleLevelOneChanged">
          <el-option
            v-for="articleClass in articleOneList"
            :key="articleClass.id"
            :label="articleClass.title"
            :value="articleClass.id"/>
        </el-select>

        <!-- 二级分类 -->
        <el-select
          v-model="article.clsId"
          placeholder="请选择">
          <el-option
            v-for="articleClass in articleTwoList"
            :key="articleClass.id"
            :label="articleClass.title"
            :value="articleClass.id"/>
        </el-select>
      </el-form-item>

      <el-form-item label="难度">
        <el-select v-model="article.difficulty" placeholder="请选择" style="width: 80px">
          <el-option
            v-for="item in difficultyOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="热度">
        <el-input-number v-model="article.sort" :min="0" :max="100000" controls-position="right" style="width: 130px"/>
      </el-form-item>

      <el-form-item label="摘要">
        <el-input v-model="article.summary" placeholder="文章摘要(别写太长)"/>
      </el-form-item>

      <el-form-item label="状态">
        <el-select v-model="article.state" placeholder="请选择" style="width: 96px">
          <el-option
            v-for="item in stateOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="内容">
        <tinymce :height="400" v-model="article.content" ref="content"/>
      </el-form-item>

      <el-form-item>
        <el-button :disabled="saveBtnDisabled" type="primary" @click="addOrEidtArticle()">{{ addOrEidtArticleTitle }}</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import articleApi from '@/api/article'
import Tinymce from '@/components/Tinymce'

export default {
  components: { Tinymce },
  data() {
    return {
      articleId: '',
      article: {
        title: '',
        summary: '',
        content: '',
        sort: 0,
        difficulty: 0,
        state: 0,
        clsId: '', // 二级分类id
        clsParentId: '', // 一级分类id
      },

      articleOneList: [], // 一级分类
      articleTwoList: [], // 二级分类

      // 难度选择下拉框
      difficultyOptions: [{
        value: 0,
        label: '简单'
      }, {
        value: 1,
        label: '中等'
      }, {
          value: 2,
          label: '困难'
      }],

      // 状态选择下拉框
      stateOptions: [{
        value: 0,
        label: '未发布'
      }, {
        value: 1,
        label: '已发布'
      }],

      // 提交文字
      addOrEidtArticleTitle: "添加"
    }
  },

  created: function () {
    if (this.$route.params && this.$route.params.id) {
      this.addOrEidtArticleTitle = "修改"
      this.articleId = this.$route.params.id
      console.log("============路由id=============")
      console.log(this.$route.params.id)
      // 调用根据id查询方法
      this.getArticleInfoById()

    } else {
      // 初始化一级分类
      this.getOneSubject()
    }
  },

  watch: {
    $route(to, from) {
      this.$refs.content.setContent("");
      this.article={
        title: '',
        summary: '',
        content: '',
        sort: 0,
        state: 0,
      }
      // 初始化一级分类
      this.getOneSubject()
    }
  },

  methods: {

    // 查询所有的一级分类
    getOneSubject() {
      articleApi.getAllArticleClasses()
        .then(response => {
          this.articleOneList = response.data.list
          console.log("====获取分类信息====")
          console.log(this.articleOneList)
        })
    },

    // 点击某个一级分类，触发change，显示对应二级分类
    articleLevelOneChanged(value) {
      // value就是一级分类id值
      // 遍历所有分类，包含一级和二级
      for (let i = 0; i < this.articleOneList.length; i++) {
        // 每个一级分类
        const oneSubject = this.articleOneList[i]
        // 判断所有一级分类id和点击的一级分类id是否相同
        if (oneSubject.id === value) {
          // 从一级分类中取出对应二级分类
          this.articleTwoList = oneSubject.children
          // 更改一级分类将二级分类清空
          this.article.clsId = ''
          // this.article.articleParentId = value
        }
      }
    },

    //根据id获取文章信息
    getArticleInfoById() {
      // 回显分类信息
      articleApi.getArticleInfoById(this.articleId)
        .then(response => {
          // 在article中包含一级分类id和二级分类id
          this.article = response.data.article
          console.log("===========获取文章===========")
          console.log(this.article)
          // 1 查询所有分类，包含一级和二级（解决数据回显二级分类显示id问题，因为二级分类对照时为空）
          articleApi.getAllArticleClasses()
            .then(response => {
              // 2 获取所有一级分类
              this.articleOneList = response.data.list
              console.log("===========获取分类===========")
              console.log(this.articleOneList)
              // 3 把所有一级分类数组进行遍历，比较当前courseId里面的一级分类id和所有的一级分类id
              for (var i = 0; i < this.articleOneList.length; i++) {
                // 获取每个一级分类
                var oneSubject = this.articleOneList[i]
                // 比较当前article里面的一级分类id和所有的一级分类id
                if (this.article.clsParentId == oneSubject.id) {
                  // 获取对应一级分类下的所有二级分类
                  this.articleTwoList = oneSubject.children
                }
              }
            })
        })
    },

    // 添加和修改文章的方法
    addOrEidtArticle() {
      console.log("===========文章状态===========")
      console.log(this.article)

      if (this.article.title===''){
        this.$message({
          message: "文章名不能为空",
          type: "warning"
        })
        return
      }
      if (this.article.summary.length>100){
        this.$message({
          message: "文章摘要字数不能大于100",
          type: "warning"
        })
        return
      }
      //修改文章
      if (this.articleId!=="") {
        this.$confirm('确定修改文章?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
            articleApi.updateArticle(this.article)
              .then(response => { // 修改成功
                // 提示信息
                this.$message({
                  type: 'success',
                  message: '修改文章成功!'
                })
                // 回到列表页面 路由跳转
                this.$router.push({path: '/article/list'})
              })
        })
      } else {
        //添加图片
        this.$confirm('确定添加文章?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          //添加图片
          articleApi.addArticle(this.article)
            .then(response => { // 添加成功
              // 提示信息
              this.$message({
                type: 'success',
                message: '添加文章成功!'
              })
              // 回到列表页面 路由跳转
              this.$router.push({path: '/article/list'})
            })
        })
      }
    },
  }
}

</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style scoped>
.tinymce-container {
  line-height: 26px;
}
</style>
